<?php
namespace app\admin\controller;
use app\util\ReturnCode;
use think\Controller;

class Base extends Controller {

    private $debug = [];
    protected $admin;
    public function initialize() {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
        header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS,PATCH');
        $token = $this->request->header('Authorization');
        $action = $this->request->action();
        if (($action != 'login') && ($action != 'doupload')) {
            if(!$token)
                exit($this->buildFailed(ReturnCode::ACCESS_TOKEN_TIMEOUT,'token过期'));

            $admin = cache('Login:' . $token);
            if(!$admin)
                exit($this->buildFailed(ReturnCode::ACCESS_TOKEN_TIMEOUT,'token过期'));

            $this->admin = json_decode($admin,true);
        }
    }

    protected function buildSuccess($data, $msg = '操作成功', $code = ReturnCode::SUCCESS) {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if ($this->debug)
            $return['debug'] = $this->debug;

        return json_encode($return);
    }

    protected function buildFailed($code, $msg, $data = []) {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if ($this->debug)
            $return['debug'] = $this->debug;

        return json_encode($return);
    }

    protected function debug($data) {
        if ($data)
            $this->debug[] = $data;
    }

    protected function buildToken(){
        do {
            $chars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $chars = str_shuffle($chars);
            $token = substr($chars, 3, 32);
            $res = cache('Login:' . $token);
        } while($res === true);

        return $token;
    }

}
